require 'yaml'
require 'webrick'
require 'jabber4r/rpc'
require 'xmpp4r'
require 'xmpp4r/client'
require 'xmpp4r/xmlrpc/helper/rpc'
require 'xmpp4r/discovery/helper/discovery_manager.rb'

include WEBrick

class CalendarServlet < HTTPServlet::AbstractServlet
  
  
  def CalendarServlet.configure()
    configuration = YAML.load_file(@@config_file)          
    @@jid = configuration['auth']['jid']+"/edsbotcli"
    @@passwd = configuration['auth']['passwd']		
    @@client_session = Jabber::Session.bind(@@jid, @@passwd)		
  end
  
  
  def CalendarServlet.config_file=(file)
    @@config_file=file
  end

  def initialize(server, config_file)
    super(server)
    @@config_file=config_file
    #CalendarServlet.configure()
  end

  def do_GET(req, res)
    #do jabber-rpc call 
    params = req.path.split("/")
    return if params.size!=4 
    params.shift
    params.shift
    user,cal= params
    client = Jabber::RPC::Client.new(@@client_session, Jabber::JID.new(user+"/edsbotsrv"))				
    res.body = client.call("get_calendar", cal)
    res['Content-Type'] = "text/icalendar"
  end
end

class CalendarHTTPServer
  attr_accessor :config_file

  def initialize(config)
    @config_file=config
  end

  def run()
    s = HTTPServer.new( :Port => 2000 )

    # HTTPServer#mount(path, servletclass)
    #   When a request referring "/hello" is received,
    #   the HTTPServer get an instance of servletclass
    #   and then call a method named do_"a HTTP method".
    CalendarServlet.config_file=@config_file
    CalendarServlet.configure()
    s.mount("/calendar", CalendarServlet, @config_file )		
    trap("HUP"){  
      puts "Configuring..."
      CalendarServlet.configure() 
    }
    trap("INT"){ s.shutdown }
    s.start
  end
end
